package cn.kai.ymcc.service.impl;

import cn.kai.ymcc.constants.YmccBusinessError;
import cn.kai.ymcc.doc.CourseDoc;
import cn.kai.ymcc.domain.*;
import cn.kai.ymcc.dto.CourseDto;
import cn.kai.ymcc.dto.MessageSendDto;
import cn.kai.ymcc.feign.CourseSearchFeignClient;
import cn.kai.ymcc.feign.MediaFileFeignClient;
import cn.kai.ymcc.mapper.CourseMapper;
import cn.kai.ymcc.mapper.CourseTeacherMapper;
import cn.kai.ymcc.mq.SendCourseMessageProducer;
import cn.kai.ymcc.result.JSONResult;
import cn.kai.ymcc.service.*;
import cn.kai.ymcc.util.AssertUtil;
import cn.kai.ymcc.util.StrUtils;
import cn.kai.ymcc.vo.CourseDetailInfoVo;
import cn.kai.ymcc.vo.CourseItemVo;
import cn.kai.ymcc.vo.CourserOrderVo;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author kai.tang
 * @since 2022-07-21
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {
    @Autowired
    private ITeacherService teacherService;
    @Autowired
    private ICourseDetailService courseDetailService;
    @Autowired
    private ICourseResourceService courseResourceService;
    @Autowired
    private ICourseMarketService courseMarketService;
    @Autowired
    private ICourseTeacherService courseTeacherService;
    @Autowired
    private ICourseTypeService courseTypeService;
    @Autowired
    private ICourseSummaryService courseSummaryService;

    @Autowired
    private CourseTeacherMapper courseTeacherMapper;
    @Autowired
    private CourseSearchFeignClient courseSearchFeignClient;
    @Autowired
    private SendCourseMessageProducer sendCourseMessageProducer;
    @Autowired
    private ICourseChapterService courseChapterService;
    @Autowired
    private MediaFileFeignClient mediaFileFeignClient;


    /**
     * 1.参数校验
     * 2.课程不能被注册
     *
     * 3.保存数据
     * 保存课程
     * 保存课程详情
     * 保存课程销售
     * 保存课程讲师
     * 保存课程资源
     * 初始化课程统计
     *
     * 课程类型表中的课程数+1
     *
     * @param dto
     */
    @Override
    @Transactional
    public void save(CourseDto dto) {
        Course course = dto.getCourse();
        CourseDetail courseDetail = dto.getCourseDetail();
        CourseMarket courseMarket = dto.getCourseMarket();
        CourseResource courseResource = dto.getCourseResource();
        List<Long> teacharIds = dto.getTeacharIds();
        //1.参数校验  JSR303=====================
        //2.课程不能被注册========================
        Course courseTmp = selectByName(course.getName());
        AssertUtil.isNull(courseTmp,"课程已被注册！！！");
        //* 3.保存数据===========================
        //* 保存课程
        // 做必要的参数的初始化  状态、讲师、  谁来添加的课程
        // 有些初始化的值，必须要在service层做填写，防止被黑客黑了
        course.setStatus(Course.STATE_OFFLINE);
        //@TODO 后面做了登录之后来补充
        course.setLoginId(1L);
        course.setLoginUserName("kaitest1");
        List<Teacher> teachers = teacherService.selectBatchIds(teacharIds);
        // 整成stream
        /*StringBuilder sb = new StringBuilder();
        teachers.forEach(teacher -> {
            sb.append(teacher.getName()).append(",");
        });*/

        String s = teachers.stream().map(Teacher::getName).collect(Collectors.joining(","));

        course.setTeacherNames(s);
        insert(course);
        //* 保存课程详情===========================
        courseDetail.setId(course.getId());
        courseDetailService.insert(courseDetail);

        //* 保存课程销售===========================
        courseMarket.setId(course.getId());
        courseMarketService.insert(courseMarket);

        //* 保存课程讲师===========================

        Map<String,Object> teacharMap = new HashMap<String,Object>();
        teacharMap.put("courseId",course.getId());
        teacharMap.put("teacharIds",teacharIds);
        courseTeacherMapper.setCourseForTeacher(teacharMap);

        /*teacharIds.forEach(id->{
            CourseTeacher courseTeacher = new CourseTeacher();
            courseTeacher.setCourseId(course.getId());
            courseTeacher.setTeacherId(id);
            courseTeacherService.insert(courseTeacher);
        });*/
        //* 保存课程资源===========================
        courseResource.setCourseId(course.getId());
        courseResourceService.insert(courseResource);

        //* 初始化课程统计===========================
        CourseSummary courseSummary = new CourseSummary();
        courseSummary.setId(course.getId());
        courseSummaryService.insert(courseSummary);

        //课程类型表中的课程数+1======================
        CourseType type = courseTypeService.selectById(course.getCourseTypeId());
        type.setTotalCount(type.getTotalCount() + 1);
        courseTypeService.updateById(type);
    }

    private Course selectByName(String name) {
        Wrapper<Course> tWrapper = new EntityWrapper<Course>();
        tWrapper.eq("name",name);
        return selectOne(tWrapper);
    }

    /**
     * 1.根据课程Id查询课程，判断可是是否存在
     * 2.修改课程状态为上架，填写上架时间
     *
     * 3.保存课程相关内容到Es
     *   3.1 为service-search编写feign接口 ymcc-api-search
     *   3.2 在课程微服务中，依赖ymcc-api-search
     *   3.3 使用feign远程调用search完成课程保存到Es中
     * @param courseId
     */
    @Override
    @Transactional
    public void onLineCourse(Long courseId) {
        //1.根据课程Id查询课程，判断可是是否存在
        Course course = selectById(courseId);
        AssertUtil.isNotNull(course, YmccBusinessError.COURSE_ERROR_EXCEPTION_NO_EMPTY.getMessage());
        boolean offLine = course.getStatus() == Course.STATE_OFFLINE;
        AssertUtil.isTrue(offLine,YmccBusinessError.COURSE_ERROR_EXCEPTION_STATUS_ERR.getMessage());
        //2.修改课程状态为上架，填写上架时间
        course.setStatus(Course.STATE_ONLINE);
        course.setOnlineTime(new Date());
        updateById(course);
        //3.保存课程相关内容到Es
        //  3.1 为service-search编写feign接口 ymcc-api-search
        //  3.2 在课程微服务中，依赖ymcc-api-search
        //  3.3 使用feign远程调用search完成课程保存到Es中
        CourseType type = courseTypeService.selectById(course.getCourseTypeId());
        CourseMarket courseMarket = courseMarketService.selectById(courseId);
        CourseSummary courseSummary = courseSummaryService.selectById(courseId);
        CourseDoc doc = new CourseDoc();
        //设置需要保存到Es的字段
        BeanUtils.copyProperties(course,doc);
        BeanUtils.copyProperties(courseMarket,doc);
        BeanUtils.copyProperties(courseSummary,doc);
        doc.setCourseTypeName(type.getName());//这里要单独赋值
        String chargeName = courseMarket.getCharge() == 1 ? "免费" : "收费";
        doc.setChargeName(chargeName);

        JSONResult result = courseSearchFeignClient.saveCourse(doc);
        AssertUtil.isTrue(result.isSuccess(),"课程发布失败");
    }

    /**
     * 课程下架
     * @param courseId
     */
    @Override
    public void offLineCourse(Long courseId) {
        //1.根据课程Id查询课程，判断是否存在,状态是否正常
        Course course = selectById(courseId);
        AssertUtil.isNotNull(course, YmccBusinessError.COURSE_ERROR_EXCEPTION_NO_EMPTY.getMessage());
        boolean offLine = course.getStatus() == Course.STATE_ONLINE;
        AssertUtil.isTrue(offLine,YmccBusinessError.COURSE_ERROR_EXCEPTION_STATUS_ERR.getMessage());
        //2.修改课程状态为下架
        course.setStatus(Course.STATE_OFFLINE);
        updateById(course);

        JSONResult result = courseSearchFeignClient.offLineCourse(courseId);
        AssertUtil.isTrue(result.isSuccess(),"课程下架失败");
    }

    /**
     * 发送推广短信
     * @param dto
     * @return
     */
    @Override
    public void sendSms(MessageSendDto dto) {
        dto.setTitle("课程发布");
        dto.setContent(dto.getCourseName()+"上线啦，快来学习！！！");
        sendCourseMessageProducer.sendSmsMessage(dto);
    }

    /**
     * 发送推广邮箱
     * @param dto
     * @return
     */
    @Override
    public void sendEmail(MessageSendDto dto) {
        dto.setTitle("课程发布");
        dto.setContent(dto.getCourseName()+"上线啦，快来学习！！！");
        sendCourseMessageProducer.sendEmailMessage(dto);
    }

    /**
     * 发送推广站内信
     * @param dto
     * @return
     */
    @Override
    public void sendStation(MessageSendDto dto) {
        dto.setTitle("课程发布");
        dto.setContent(dto.getCourseName()+"上线啦，快来学习！！！");
        dto.setType("系统消息");
        sendCourseMessageProducer.sendStationMessage(dto);
    }

    /**
     * 查询课程详情
     * @param courseId
     * @return
     */
    @Override
    public CourseDetailInfoVo searchCourseDetail(Long courseId) {
        AssertUtil.isNotNull(courseId,"请求非法");
        Course course = selectById(courseId);
        AssertUtil.isNotNull(course,"请求非法");
        boolean onLine = course.getStatus() == Course.STATE_ONLINE;
        AssertUtil.isTrue(onLine,"请求非法");//课程没有上线

        CourseDetail courseDetail = courseDetailService.selectById(courseId);
        CourseMarket courseMarket = courseMarketService.selectById(courseId);
        CourseSummary courseSummary = courseSummaryService.selectById(courseId);
        Wrapper<CourseTeacher> ctwrapper = new EntityWrapper<>();
        ctwrapper.eq("course_id",courseId);
        List<CourseTeacher> courseTeachers = courseTeacherService.selectList(ctwrapper);
        List<Long> teacherIds = courseTeachers.stream().map(teacher -> teacher.getTeacherId()).collect(Collectors.toList());
        List<Teacher> teachers = teacherService.selectBatchIds(teacherIds);
        //查询章节
        Wrapper<CourseChapter> ccwrapper = new EntityWrapper<>();
        ccwrapper.eq("course_id",courseId);
        List<CourseChapter> chapters = courseChapterService.selectList(ccwrapper);
        //要为每一个章节查询对应的视屏
        //1.media微服务编写controller查询章节视屏
        //2.为media服务编写Feign接口+降级方案
        //3.course微服务依赖media的Feign接口，调用media查询章节视屏
        chapters.forEach(chapter->{
            JSONResult jsonResult = mediaFileFeignClient.searchMediaFiles(chapter.getId());//你可以搞成批量查询
            if(jsonResult.isSuccess() && jsonResult.getData() != null){
                List<MediaFile> fileList = JSONObject.parseArray(jsonResult.getData().toString(), MediaFile.class);
                chapter.getMediaFiles().addAll(fileList);
            }
        });
        CourseDetailInfoVo vo = new CourseDetailInfoVo();
        vo.setCourse(course);
        vo.setCourseChapters(chapters);
        vo.setCourseMarket(courseMarket);
        vo.setCourseSummary(courseSummary);
        vo.setCourseDetail(courseDetail);
        vo.setTeachers(teachers);
        return vo;
    }

    /**
     * 1.判断参数
     * 2.业务判断
     * 2.根据每个课程Id查询课程 + 销售表
     * 3.封装课程和销售成 CourseItemVo
     * 4.将封装好的List<CourseItemVo> + 总金额，封装成CourserOrderVo
     * @param courseIds  3,9   3,3
     * @return
     */
    @Override
    public CourserOrderVo courserOrderVo(String courseIds) {
        List<Long> ids = StrUtils.splitStr2LongArr(courseIds);
        Set<Long> setIds = ids.stream().collect(Collectors.toSet());
        //1.判断参数
        //2.业务判断
        boolean ok = ids.size() == setIds.size();//id个数是否相等。没有传递重复ID
        AssertUtil.isTrue(ok,"请求非法！");
        //2.根据每个课程Id查询课程 + 销售表
        List<CourseItemVo> courseInfos = new ArrayList<>();
        BigDecimal totalAmount = new BigDecimal(0);
        for (Long id : setIds) {
            //3.封装课程和销售成 CourseItemVo
            Course course = selectById(id);
            AssertUtil.isNotNull(course,"请求非法！");
            //课程不能上线
            boolean online = course.getStatus() == Course.STATE_ONLINE;
            AssertUtil.isTrue(online,"请求非法！！");
            CourseMarket courseMarket = courseMarketService.selectById(id);
            AssertUtil.isNotNull(courseMarket,"请求非法！");
            CourseItemVo courseItemVo = new CourseItemVo(course, courseMarket);
            courseInfos.add(courseItemVo);
            totalAmount = totalAmount.add(courseMarket.getPrice());
        }
        //4.将封装好的List<CourseItemVo> + 总金额，封装成CourserOrderVo
        return new CourserOrderVo(courseInfos,totalAmount);
    }
}
